package pactice_handler

import (
	"encoding/json"
	"fmt"
	"net/http"
	"peilian-api/app/global/bind"
	"peilian-api/app/global/databases/elastic"
	"peilian-api/app/global/databases/tables"
	"peilian-api/app/global/errors"
	"peilian-api/app/global/variable"
	"peilian-api/app/model"
	"peilian-api/app/services/report_service"
	"peilian-api/app/services/view_service"
	"peilian-api/utils/format"

	"github.com/gin-gonic/gin"
)

//func JudgeSessionFirst(ctx *gin.Context) {
//	out, _ := new(report_service.SessionService).JudgeSessionFirst(ctx)
//	format.NewResponseJson(ctx).SuccessObj(struct {
//		IsFirst bool `json:"is_first"`
//	}{
//		IsFirst: out,
//	})
//}

// 满意度调查
func SessionSatisfied(ctx *gin.Context) {
	var sfs model.SatisfiedScore
	if err := bind.ShouldBinding(ctx, &sfs); err != nil {
		format.NewResponseJson(ctx).SuccessObjMsg(30001, errors.ParamBindError)
		return
	}
	_, er := new(report_service.SessionService).SessionSatisfied(ctx, sfs)
	if er != nil {
		format.NewResponseJson(ctx).SuccessObjMsg(30002, er.Err.Error())
		return
	}
	format.NewResponseJson(ctx).SuccessObj(struct{}{})
}

func ExceedPercent(c *gin.Context) {
	sessionId := c.Param("sessionId")
	var session tables.Session
	if err := variable.DB.MySQL.Select("TotalScore", "CareerName").First(&session, sessionId).Error; err != nil {
		format.NewResponseJson(c).ErrObj(http.StatusBadRequest, err.Error())
		return
	}
	query := elastic.NewTermQuery("career_name", session.CareerName)
	startItem := &elastic.SplitItem{Key: fmt.Sprintf("%f以下", session.TotalScore), To: session.TotalScore}
	endItem := &elastic.SplitItem{Key: fmt.Sprintf("%f以上", session.TotalScore), From: session.TotalScore}
	aggs := elastic.NewRangeAggregation("score").RangeItem(startItem).RangeItem(endItem)
	res, err := elastic.NewEsClient().Size(0).Query(query).Aggregation("exceed_percent", aggs).Search()
	if err != nil {
		format.NewResponseJson(c).ErrObj(http.StatusBadRequest, err.Error())
		return
	}
	var esResp view_service.EsAggregationRes
	_ = json.Unmarshal(res, &esResp)
	exceedPercent := float64(esResp.Aggregation.ExceedPercent.Buckets[0].DocCount) / float64(esResp.Hits.Total.Value)
	format.NewResponseJson(c).SuccessObj(fmt.Sprintf("%.2f%%", exceedPercent*100))
}
